#include "PandorabotClient.h"

#define CHUNK_SIZE		2048

const std::string PandorabotComRootURL = "www.pandorabots.com";
const std::string PandorabotComTalkLoc = "/pandora/talk-xml";

std::string reply(std::string botId, std::string input)
{  
    std::string returnMessage;
    
    try
    {
        //	1. Instantiate CInternetSession
        CInternetSession httpSession(_T("Pandorabot Client"), 
            1,
            INTERNET_OPEN_TYPE_PRECONFIG,
            NULL,
            NULL,
            INTERNET_FLAG_DONT_CACHE);

        //	2. Get CHttpConnection (Server URL and Port required)
        CHttpConnection* pHttpConnection = httpSession.GetHttpConnection(
            _T(PandorabotComRootURL.c_str()), 
            INTERNET_FLAG_NO_AUTO_REDIRECT,
            80, 
            NULL, 
            NULL);

        //	3. Open HTTP Request (pass method type [get/post/..] and URL path (except server name))
        CHttpFile* pHttpFile = pHttpConnection->OpenRequest(
            _T("POST"), 
            _T(PandorabotComTalkLoc.c_str()), 
            NULL, 
            1, 
            NULL, 
            NULL, 
            INTERNET_FLAG_EXISTING_CONNECT |
                INTERNET_FLAG_DONT_CACHE |
                INTERNET_FLAG_RELOAD);

        //	4. Add HTTP Request Headers
        std::string strPOSTdata = "botid=" + botId + "&input=" + input;
        CString strPOSTReq(strPOSTdata.c_str());
        DWORD dwRewLen = strPOSTReq.GetLength();
        CString strHeaders;
        strHeaders.Format(_T("Content-Type: application/x-www-form-urlencoded; charset=utf-8\nContent-Length: %d"), 
            dwRewLen);
        pHttpFile->AddRequestHeaders(strHeaders);

        //	5. Send the request
        pHttpFile->SendRequest(NULL, 0, (LPVOID)(LPCTSTR)strPOSTReq, dwRewLen);

        //	6. Check the return HTTP Status Code
        DWORD dwStatucCode = HTTP_STATUS_OK;

        pHttpFile->QueryInfoStatusCode(dwStatucCode);

        if(dwStatucCode == HTTP_STATUS_OK)
        {
            CString strResponse;
            TCHAR szBuf[CHUNK_SIZE] = {0};
            UINT nBytesRead;

            //	7. Read the response text
            do
            {
                nBytesRead = pHttpFile->Read((void*) szBuf, CHUNK_SIZE);
                strResponse += szBuf;
                if(nBytesRead < CHUNK_SIZE)
                    break;
            }while(nBytesRead == CHUNK_SIZE);

            std::string xmlStr = strResponse;

            size_t bIdx = xmlStr.find("<that>");
            size_t eIdx = xmlStr.find("</that>");

            if (bIdx != std::string::npos)
            {
                returnMessage = xmlStr.substr(bIdx + 6, eIdx - bIdx - 6);      
            }
            else
            {
                bIdx = xmlStr.find("<message>");
                eIdx = xmlStr.find("</message>");
                returnMessage = xmlStr.substr(bIdx + 9, eIdx - bIdx - 9);
            }
        }
        else
        {
            returnMessage = "Error. Unexpected HTTP return code.";
        }

        //	8. Close the stream/connection
        if(pHttpFile)
        {
            pHttpFile->Close();
            delete pHttpFile;
            pHttpFile = NULL;
        }

        if(pHttpConnection)
        {
            pHttpConnection->Close();
            delete pHttpConnection;
            pHttpConnection = NULL;
        }

    }
    catch(CInternetException* exp)
    {
        TCHAR lpszErrorMsg[MAX_PATH+2];
        exp->GetErrorMessage(lpszErrorMsg, MAX_PATH);
        returnMessage = lpszErrorMsg;
    }

    return returnMessage;
}


